import React from 'react';
import Map from 'ol/Map';
import View from 'ol/View';
import Tile from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

import LayerVector from 'ol/layer/Vector';
import SourceVector from 'ol/source/Vector';
import Draw, { createRegularPolygon, createBox } from 'ol/interaction/Draw';
import { fromLonLat } from 'ol/proj';

import { Tooltip, Space } from 'antd';
import Style from 'ol/style/Style';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Circle from 'ol/style/Circle';
// import { defaults as controlDefaults, ZoomSlider, ZoomToExtent } from 'ol/control';

import styles from './index.less';

import { createFromIconfontCN } from '@ant-design/icons';
const IconFont = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_3318073_0x3s9p4v8rxl.js',
});

export default class TestMap extends React.PureComponent {
  mapRef = null;
  map = null;
  draw = null;
  drawStyle = new Style({
    fill: new Fill({
      color: 'rgba(0, 0, 255, .2)',
    }),
    stroke: new Stroke({
      color: 'rgba(0, 0, 255, .6)',
      width: 2,
    }),
    image: new Circle({
      fill: new Fill({
        color: 'rgba(0, 0, 255, .6)',
      }),
      radius: 8,
    }),
  });
  mapInteractionSource = new SourceVector({ wrapX: false });
  state = {
    active: '',
    features: [],
  };

  constructor(props) {
    super(props);
  }

  componentDidMount = () => {
    this.map = new Map({
      // 设置挂载点为map
      target: this.mapRef,
      // 设置图层
      layers: [
        new Tile({
          source: new OSM(),
        }),
        // 绘制图层
        new LayerVector({
          source: this.mapInteractionSource,
          // 绘制的图形颜色
          style: this.drawStyle,
        }),
      ],
      // 设置地图的可视区域，center为中心点，zoom为缩放的层级
      view: new View({
        center: fromLonLat([113.252, 23.15]),
        zoom: 16,
      }),
      // 去除放大、缩小等控件
      controls: [],
    });
  };

  /**
   * @description 清除
   */
  handleClear = () => {
    this.setState({
      active: '',
      features: [],
    });

    if (this.draw) {
      this.map.removeInteraction(this.draw);
    }

    // 取消绘制
    this.draw = null;
    // 清除绘制
    this.mapInteractionSource.clear();
  };

  /**
   * @description 绘制
   * @param {*} type 绘制类型
   */
  handleDraw = (type) => {
    this.setState({
      active: type,
      // 重新修改 features 还原
      features: [],
    });

    if (this.draw) {
      this.map.removeInteraction(this.draw);
      if (type === this.state.active) {
        this.setState({
          active: '',
        });
        return;
      }
    }

    let geometryFunction;
    switch (type) {
      // 画矩形
      case 'Square':
        type = 'Circle';
        geometryFunction = createBox(4);
        break;
      // 画正方形 - 没使用
      case 'Box':
        type = 'Circle';
        geometryFunction = createRegularPolygon(4);
      default:
        break;
    }

    this.draw = new Draw({
      source: this.mapInteractionSource,
      type,
      geometryFunction,
      // 绘制的图形颜色
      style: this.drawStyle,
    });
    this.map.addInteraction(this.draw);
  };

  /**
   * @description 撤销
   */
  handlePrev = () => {
    // 获取 features
    const features = this.mapInteractionSource.getFeatures();
    const feature = features.pop();
    // 移除 feature
    if (feature) {
      this.mapInteractionSource.removeFeature(feature);
      this.setState((state) => {
        state.features.push(feature);
        return {
          features: state.features,
        };
      });
    }
  };

  /**
   * @description 还原
   */
  handleNext = () => {
    let feature;
    this.setState(
      (state) => {
        feature = state.features.pop();
        return {
          features: state.features,
        };
      },
      () => {
        if (feature) {
          this.mapInteractionSource.addFeature(feature);
        }
      },
    );
  };

  render = () => {
    return (
      <div className={styles.testMap} ref={(ref) => (this.mapRef = ref)}>
        <Space size="middle" className={styles.drawActions}>
          <Tooltip placement="top" title="标点">
            <IconFont
              className={this.state.active === 'Point' && styles.active}
              type="icon-biaodiandidian_"
              onClick={this.handleDraw.bind(this, 'Point')}
            />
          </Tooltip>
          <Tooltip placement="top" title="画线">
            <IconFont
              className={this.state.active === 'LineString' && styles.active}
              type="icon-guizeyinqing"
              onClick={this.handleDraw.bind(this, 'LineString')}
            />
          </Tooltip>
          <Tooltip placement="top" title="画矩形">
            <IconFont
              className={this.state.active === 'Square' && styles.active}
              type="icon-mian"
              onClick={this.handleDraw.bind(this, 'Square')}
            />
          </Tooltip>
          <Tooltip placement="top" title="画圆">
            <IconFont
              className={this.state.active === 'Circle' && styles.active}
              type="icon-xingzhuang-tuoyuanxing"
              onClick={this.handleDraw.bind(this, 'Circle')}
            />
          </Tooltip>
          <Tooltip placement="top" title="画多边形">
            <IconFont
              className={this.state.active === 'Polygon' && styles.active}
              type="icon-draw-polygon"
              onClick={this.handleDraw.bind(this, 'Polygon')}
            />
          </Tooltip>
          <Tooltip placement="top" title="撤销">
            <IconFont type="icon-fanhui" onClick={this.handlePrev} />
          </Tooltip>
          <Tooltip placement="top" title="还原">
            <IconFont type="icon-qianjin" onClick={this.handleNext} />
          </Tooltip>
          <Tooltip placement="top" title="清除">
            <IconFont type="icon-qingchu" onClick={this.handleClear} />
          </Tooltip>
        </Space>
      </div>
    );
  };
}
